package com.itheima.shiro.realm;

import com.itheima.shiro.service.impl.SecurityServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class DefinitionRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 从authenticationToken获取登录名称
        String loginName = (String) authenticationToken.getPrincipal();
        SecurityServiceImpl securityService = new SecurityServiceImpl();
        String password = securityService.findPasswordByLoginName(loginName);

        if (password == null || "".equals(password)) {
            throw new UnknownAccountException("账户不存在");
        }

        // 传递账号和密码
        return new SimpleAuthenticationInfo(loginName, password, getName());
    }
}
